from django.shortcuts import render, HttpResponse, redirect
from web.forms.project import ProjectModelForm
from django.http import JsonResponse
from web import models


def project_list(request):
    """项目列表"""
    if request.method == "GET":
        """
        思路:
        1.从数据库获取两部分数据
            我创建的所有项目：已经星标：没有星标：
            我参与的所有项目：已经星标：没有星标：
        2.提取已经星标
            列表 = 循环[我创建的所有项目] + [我参与的所有项目] 把已经星标的提取
        得到三个列表：星标、创建、参与
        """
        # get请求查看项目
        project_dict = {'star': [], 'my': [], 'join': []}

        # 我创建的项目
        my_project_list = models.Project.objects.filter(creator=request.tracer.user)
        for row in my_project_list:
            if row.star:
                project_dict['star'].append({"value": row, "type": "my"})
            else:
                project_dict['my'].append(row)

        # 我参与的项目
        join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)
        for item in join_project_list:
            if item.star:
                project_dict['star'].append({"value": item.project, "type": "my"})
            else:
                project_dict['join'].append(item.project)

        form = ProjectModelForm(request)
        return render(request, 'web/project_list.html', {'form': form, 'project_dict': project_dict})

    # post请求新建项目
    form = ProjectModelForm(request, data=request.POST)
    if form.is_valid():
        # 验证通过:用户提交了项目名，颜色，描述 +creator创建者
        form.instance.creator = request.tracer.user
        # 创建项目
        form.save()
        return JsonResponse({'status': True})

    # 验证数据错误
    return JsonResponse({'status': False, 'error': form.errors})


def project_star(request, project_type, project_id):
    """星标项目"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
        return redirect('project_list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=True)
    return HttpResponse("请求错误")


def project_unstar(request, project_type, project_id):
    """取消星标"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
        return redirect('project_list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=False)
    return HttpResponse("请求错误")
